//
//  main.c
//  forktest
//
//  Created by 杨岑 on 6/22/15.
//  Copyright (c) 2015 杨岑. All rights reserved.
//

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <util.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char** argv, char** environ)
{
    int master = 0;
    char name[300] = {0};
    
    printf("In parent process: %d\n", getpid());
    pid_t t = forkpty(&master, name, 0, 0);
    if (t > 0)
    {
        char buf[100] = {0};
        char* cmd = ".show\n.q\n";
        
        printf("In parent (child pid: %d, master pty: %d %s)\n", t, master, name);
        write(master, cmd, strlen(cmd));
        for (;;)
        {
            ssize_t n = read(master, buf, 99);
            if (n > 0)
            {
                buf[n] = 0;
                printf("%s", buf);
            }
            else
            {
                if (n < 0)
                {
                    printf("Reading error: %d\n", errno);
                }
                break;
            }
        }
        puts("End of reading");
    }
    else if (t == 0)
    {
        int n = 0;
        for (; environ[n]; n++)
        {
            printf("%d:%s\n", n, environ[n]);
        }
        n++;
        printf("n = %d\n", n);
        
        char** envp = malloc((n + 1) * sizeof(char*));
        for (int i = 0; i < n; i++)
        {
            envp[i] = environ[i];
        }
        envp[n - 1]  = "TERM=ansi";
        envp[n] = 0;
        //char* const my_argv[] = {"--help", 0};
        
        printf("In child: %d\n", getpid());
        execve("/usr/local/bin/sqlite3", 0, envp);
        // execve should never return
        printf("execve failed: %d\n", errno);
    }
    else
    {
        printf("Fork error: %d\n", errno);
    }
    
    if (t == 0)
    {
        getchar();
        puts("Parent ending");
    }
    return 0;
}

